package com.lingjtx.iot.network.common;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.retry.support.RetryTemplate;

@Slf4j
public class ErrorMessageHandler implements MessageHandler {
    private final RetryTemplate retryTemplate;

    public ErrorMessageHandler(RetryTemplate retryTemplate) {
        this.retryTemplate = retryTemplate;
    }

    @SneakyThrows
    @Override
    public void handleMessage(Message<?> message) {
        Throwable cause = (Throwable) message.getPayload();
        log.error("MQTT error occurred", cause);

        if (cause instanceof MqttException) {
            retryTemplate.execute(context -> {
                log.info("Retrying connection attempt {}", context.getRetryCount());
                // 触发重连逻辑
                throw new MqttException(cause);
            });
        }
    }
}
